/**
 * @version V1.0
 * @Title:
 * @Package
 * @Description:
 * @author: runoob
 * @date:
 */

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CropImage extends JFrame{
    private static int exampleX;
    private static int exampleY;
    private static int magniExX = 160;
    private static int magniExY = 160;
    private static int miniExX = 160;
    private static int miniExY = 160;
    private static int imageX;
    private static int imageY;
    private static int cacheX = 0;
    private static int cacheY = 0;
    private int num = 0;
    private int width = 0;
    private int height = 0;
    private ImagePanel image;
    private BufferedImage cache;
    private JPanel editArea = new JPanel();
    private JFileChooser jfc = new JFileChooser(new File("."));
    private static BufferedImage magniExImg;
    private static BufferedImage miniExImg;
    private ImagePanel magniEx = new ImagePanel("resources/image/magniEx.png");
    private ImagePanel miniEx = new ImagePanel("resources/image/miniEx.png");
    private JPanel colorPanel = new JPanel(); //用于反映颜色变化的面板
    private Boolean isMagni = true;
    private String name = "";
    private Color color = Color.WHITE;
    private JButton miniBtn;

    public void start() throws IOException {

        magniExImg = ImageIO.read(new File("resources/image/magniEx.png"));
        miniExImg = ImageIO.read(new File("resources/image/miniEx.png"));

        JPanel main = (JPanel) this.getContentPane();
        main.setLayout(null);
        main.setBackground(Color.GRAY);
        editArea.setLayout(null);
        editArea.setBounds(10,60,600,620);
        editArea.setBackground(Color.GRAY);
        editArea.setBorder(new LineBorder(Color.BLACK));
        cache = ImageIO.read(new File("resources/image/pa.png"));
        image = new ImagePanel(cache.getScaledInstance(600,620,Image.SCALE_SMOOTH));
        image.setBounds(0,0,600,620);

        colorPanel.setBounds(10,700,600,20);

        magniEx.setBounds(160,160,302,362);		//先初始化JLabel位置
        magniEx.setBorder(new LineBorder(Color.BLACK));
        magniEx.addMouseListener(new MouseAdapter() {		//鼠标点击事件
            public void mousePressed(MouseEvent e) {
                exampleX = e.getPoint().x;		//获取鼠标在组件内x坐标并赋值给mlx（组件坐标系）
                exampleY = e.getPoint().y;		//获取鼠标在组件内y坐标并赋值给mly（组件坐标系）
            }
        });
        magniEx.addMouseMotionListener(new MouseMotionAdapter() {		//鼠标拖动事件
            public void mouseDragged(MouseEvent e) {
                magniExX = e.getXOnScreen()-getX()-exampleX-15;
                magniExY = e.getYOnScreen()-getY()-exampleY-85;
                magniEx.setBounds(magniExX,magniExY,302,362);
                refresh();
            }
        });
        miniEx.setBounds(160,160,302,247);		//先初始化JLabel位置
        miniEx.setBorder(new LineBorder(Color.BLACK));
        miniEx.addMouseListener(new MouseAdapter() {		//鼠标点击事件
            public void mousePressed(MouseEvent e) {
                exampleX = e.getPoint().x;		//获取鼠标在组件内x坐标并赋值给mlx（组件坐标系）
                exampleY = e.getPoint().y;		//获取鼠标在组件内y坐标并赋值给mly（组件坐标系）
            }
        });
        miniEx.addMouseMotionListener(new MouseMotionAdapter() {		//鼠标拖动事件
            public void mouseDragged(MouseEvent e) {
                miniExX = e.getXOnScreen()-getX()-exampleX-15;
                miniExY = e.getYOnScreen()-getY()-exampleY-85;
                miniEx.setBounds(miniExX,miniExY,302,247);
                refresh();
            }
        });

        JButton magniBtn = new JButton("编辑正常模式背景");
        magniBtn.setIcon(new ImageIcon("resources/image/info.png"));
        magniBtn.setFont(new Font("微软雅黑", Font.BOLD, 12));
        magniBtn.setForeground(Color.WHITE);
        magniBtn.setVerticalTextPosition(JLabel.CENTER);
        magniBtn.setHorizontalTextPosition(JLabel.CENTER);
        magniBtn.setBounds(80,15,200,30);
        miniBtn = new JButton("编辑迷你模式背景");
        miniBtn.setIcon(new ImageIcon("resources/image/info.png"));
        miniBtn.setFont(new Font("微软雅黑", Font.BOLD, 12));
        miniBtn.setForeground(Color.WHITE);
        miniBtn.setVerticalTextPosition(JLabel.CENTER);
        miniBtn.setHorizontalTextPosition(JLabel.CENTER);
        miniBtn.setBounds(350,15,200,30);
        JButton chooseBtn = new JButton("选择文件");
        chooseBtn.setIcon(new ImageIcon("resources/image/info.png"));
        chooseBtn.setFont(new Font("微软雅黑", Font.BOLD, 12));
        chooseBtn.setForeground(Color.WHITE);
        chooseBtn.setVerticalTextPosition(JLabel.CENTER);
        chooseBtn.setHorizontalTextPosition(JLabel.CENTER);
        chooseBtn.setBounds(35,740,150,30);
        JButton saveBtn = new JButton("生成背景");
        saveBtn.setIcon(new ImageIcon("resources/image/info.png"));
        saveBtn.setFont(new Font("微软雅黑", Font.BOLD, 12));
        saveBtn.setForeground(Color.WHITE);
        saveBtn.setVerticalTextPosition(JLabel.CENTER);
        saveBtn.setHorizontalTextPosition(JLabel.CENTER);
        saveBtn.setBounds(445,740,150,30);
        JButton updateBtn = new JButton("选择颜色");
        updateBtn.setIcon(new ImageIcon("resources/image/info.png"));
        updateBtn.setFont(new Font("微软雅黑", Font.BOLD, 12));
        updateBtn.setForeground(Color.WHITE);
        updateBtn.setVerticalTextPosition(JLabel.CENTER);
        updateBtn.setHorizontalTextPosition(JLabel.CENTER);
        updateBtn.setBounds(240,740,150,30);
        magniBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addMagniEx();
            }
        });
        miniBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addMiniEx();
            }
        });
        chooseBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                openFileChooser();
            }
        });
        saveBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    if (isMagni){
                        name = JOptionPane.showInputDialog("请输入主题名：");
                    }
                    draggedScreen(0);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
        updateBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JColorChooser chooser = new JColorChooser();    //实例化颜色选择器
                color = chooser.showDialog(CropImage.this,"选取颜色",color);  //得到选择的颜色
                colorPanel.setBackground(color);  //改变面板的背景色
                refreshMagniEx();
                miniEx = new ImagePanel(ItemColorChange.change(miniExImg,color.getRed(),color.getGreen(),color.getBlue()));
            }
        });

        editArea.add(image);
        main.add(editArea);
        main.add(colorPanel);
        main.add(magniBtn);
        main.add(miniBtn);
        main.add(chooseBtn);
        main.add(updateBtn);
        main.add(saveBtn);
        int screenWidth= java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
        int screenHeight = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;
        //设置窗体大小
        this.setBounds((screenWidth-630)/2, (screenHeight-800)/2, 630, 820);
        this.setResizable(false);
        this.setVisible(true);
        this.setTitle("时钟主题编辑器");
        //设置图标
        BufferedImage image = ImageIO.read(new File("resources/image/crop.png"));
        this.setIconImage(image);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void refreshMagniEx(){
        editArea.remove(magniEx);
        magniEx = new ImagePanel(ItemColorChange.change(magniExImg,color.getRed(),color.getGreen(),color.getBlue()));
        magniEx.setBounds(magniExX,magniExY,302,362);		//先初始化JLabel位置
        magniEx.setBorder(new LineBorder(Color.BLACK));
        magniEx.addMouseListener(new MouseAdapter() {		//鼠标点击事件
            public void mousePressed(MouseEvent e) {
                exampleX = e.getPoint().x;		//获取鼠标在组件内x坐标并赋值给mlx（组件坐标系）
                exampleY = e.getPoint().y;		//获取鼠标在组件内y坐标并赋值给mly（组件坐标系）
            }
        });
        magniEx.addMouseMotionListener(new MouseMotionAdapter() {		//鼠标拖动事件
            public void mouseDragged(MouseEvent e) {
                magniExX = e.getXOnScreen()-getX()-exampleX-15;
                magniExY = e.getYOnScreen()-getY()-exampleY-85;
                magniEx.setBounds(magniExX,magniExY,302,362);
                refresh();
            }
        });
        editArea.add(magniEx);
        editArea.remove(image);
        editArea.add(image);
        refresh();
    }

    public void refreshMiniEx(){
        editArea.remove(miniEx);
        miniEx = new ImagePanel(ItemColorChange.change(miniExImg,color.getRed(),color.getGreen(),color.getBlue()));
        miniEx.setBounds(miniExX,miniExY,302,247);//先初始化JLabel位置
        miniEx.setBorder(new LineBorder(Color.BLACK));
        miniEx.addMouseListener(new MouseAdapter() {		//鼠标点击事件
            public void mousePressed(MouseEvent e) {
                exampleX = e.getPoint().x;		//获取鼠标在组件内x坐标并赋值给mlx（组件坐标系）
                exampleY = e.getPoint().y;		//获取鼠标在组件内y坐标并赋值给mly（组件坐标系）
            }
        });
        miniEx.addMouseMotionListener(new MouseMotionAdapter() {		//鼠标拖动事件
            public void mouseDragged(MouseEvent e) {
                miniExX = e.getXOnScreen()-getX()-exampleX-15;
                miniExY = e.getYOnScreen()-getY()-exampleY-85;
                miniEx.setBounds(miniExX,miniExY,302,247);
                refresh();
            }
        });
    }

    public void addMagniEx(){
        isMagni = true;
        editArea.remove(miniEx);
        editArea.add(magniEx);
        editArea.remove(image);
        editArea.add(image);
        refresh();
    }

    public void addMiniEx(){
        refreshMiniEx();
        isMagni = false;
        editArea.remove(magniEx);
        editArea.add(miniEx);
        editArea.remove(image);
        editArea.add(image);
        refresh();
    }

    public void change(){
        int widthCache = width - width * num / 100;
        int heightCache = height - height * num / 100;
        editArea.remove(image);
        image = new ImagePanel(cache.getScaledInstance(widthCache,heightCache,Image.SCALE_SMOOTH));
        image.setBounds(cacheX,cacheY,widthCache,heightCache);
        image.addMouseWheelListener(e -> {
            num += e.getWheelRotation();
            change();
        });
        image.addMouseListener(new MouseAdapter() {		//鼠标点击事件
            public void mousePressed(MouseEvent e) {
                imageX = e.getPoint().x;		//获取鼠标在组件内x坐标并赋值给mlx（组件坐标系）
                imageY = e.getPoint().y;		//获取鼠标在组件内y坐标并赋值给mly（组件坐标系）
            }
        });
        image.addMouseMotionListener(new MouseMotionAdapter() {		//鼠标拖动事件
            public void mouseDragged(MouseEvent e) {
                cacheX = e.getXOnScreen()-getX()-imageX-10;
                cacheY = e.getYOnScreen()-getY()-imageY-85;
                image.setBounds(cacheX,cacheY,widthCache,heightCache);
                refresh();
            }
        });
        editArea.add(image);
        refresh();
    }

    public void refresh(){
        this.invalidate();
        this.validate();
        this.repaint(100);
    }

    public void openFileChooser(){
        //打开文件选择器对话框
        int status = jfc.showOpenDialog(this);
        //没有选打开按钮结果提示
        if(status!=JFileChooser.APPROVE_OPTION){
//            ta.setText("没有选中文件");
        } else{
            try {
                //被选中的文件保存为文件对象
                File file = jfc.getSelectedFile();
                ImagePanel im = new ImagePanel(file.getAbsolutePath());
                if (im.getWidth()/im.getHeight() >= 10/11){
                    width = 600;
                    height = im.getHeight()*600/im.getWidth();
                }else {
                    width = im.getWidth()*660/im.getHeight();
                    height = 660;
                }
                cache = ImageIO.read(file);
                editArea.add(magniEx);
                change();
            } catch (FileNotFoundException e1) {
                System.out.println("系统没有找到此文件");
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void draggedScreen(int i)throws Exception {
        File dir = new File("resources/image/SKIN_" + name);
        if(!dir.exists()){//如果文件夹不存在
            dir.mkdir();//创建文件夹
        }
        createProperties();
        if (isMagni){
            int x = magniExX - cacheX;
            int y = magniExY - cacheY;
            File file = new File("resources/image/cache.png");
            ImageIO.write(dealImage(x,y,300,360), "PNG", file);
            if (i == 0){
                crop("lunchBar",0,0,300,30);
                crop("bg",0,30,300,165);
                crop("memo",0,196,300,165);
                crop("editbg",0,0,300,240);
            }else {
                update("lunchBar",0,0,300,30);
                update("bg",0,30,300,165);
                update("memo",0,196,300,165);
                update("editbg",0,0,300,240);
            }
            file.delete();
            JOptionPane.showMessageDialog(null,"生成正常模式背景成功！请继续编辑迷你模式！");
            miniBtn.requestFocus();
            addMiniEx();
        }else {
            int x = miniExX - cacheX;
            int y = miniExY - cacheY;
            File file = new File("resources/image/cache.png");
            ImageIO.write(dealImage(x,y,300,275), "PNG", file);
            if (i == 0){
                crop("lunchMiniBar",0,0,300,30);
                crop("bgMini",0,30,300,80);
                crop("memoMIni",0,111,300,165);
            }else {
                update("lunchMiniBar",0,0,300,30);
                update("bgMini",0,30,300,80);
                update("memoMIni",0,111,300,165);
            }
            file.delete();
            JOptionPane.showMessageDialog(null,"生成迷你模式背景成功！请到时钟主题管理中更换主题！");
            this.dispose();
        }

    }

    public BufferedImage dealImage(int x,int y,int width,int height){
        int widthCache = this.width - this.width * num / 100;
        int heightCache = this.height - this.height * num / 100;
        BufferedImage img = new BufferedImage(widthCache, heightCache, BufferedImage.TYPE_INT_RGB);
        Graphics2D biContext = img.createGraphics();
        biContext.drawImage(cache.getScaledInstance(widthCache,heightCache,Image.SCALE_SMOOTH), 0, 0, null);
        return ImageKit.crop(img,x,y,width,height);
    }

    public void crop(String name,int left,int top,int width,int height) throws IOException {
        BufferedImage cache = ImageKit.crop("resources/image/cache.png",left,top,width,height);
        File file = new File("resources/image/SKIN_" + this.name + "/" + name + ".png");
        ImageIO.write(cache, "PNG", file);
    }

    public void update(String name,int left,int top,int width,int height) throws IOException {
        BufferedImage cache = ImageKit.crop("resources/image/cache.png",left,top,width,height);
        File file = new File("resources/image/SKIN_" + this.name + "/" + name + ".png");
        ImageIO.write(cache, "PNG", file);
    }

    public void createProperties(){
        PropertiesUtil properties = new PropertiesUtil();
        Map<String ,String> cache = new HashMap<>();
        cache.put("time.font","LESLIEB_");
        cache.put("date.font","ZiTiQuanXinYiGuanHeiTi-2");
        cache.put("other.font","简约字体");
        cache.put("font.r",color.getRed()+"");
        cache.put("font.g",color.getGreen()+"");
        cache.put("font.b",color.getBlue()+"");
        cache.put("btn.r",color.getRed()+"");
        cache.put("btn.g",color.getGreen()+"");
        cache.put("btn.b",color.getBlue()+"");
        cache.put("date.size","16");
        cache.put("time.size","60");
        cache.put("other.size","16");
        properties.update(cache,"resources/image/SKIN_" + this.name + "/" + "FONT.properties");
    }

}